// pages/addressList/addressList.js
const {
  deleteAddress,
  addressList,
  editAddress
} = require('../../api/url.js')
const cityData = require('../../utils/cityData')
import {
  formatAddrCodeToString,
  formatRegion
} from '../../utils/util.js'
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    user: {}, //用户信息
    list: [], //地址列表
    enableSelect: null, //是否激活地址选择
    isIPX:false,//是否是iphoneX
  },
  //读取地址信息
  loadAddress: function() {
    var self = this
    const {
      user
    } = this.data
    wx.showLoading({
      title: '加载中',
    })
    wx.request({
      url: addressList,
      data: {
        fUserId: user.id,
        token: wx.getStorageSync('token'),
        loginName: user.loginname,
      },
      success: function(res) {
        wx.hideLoading()
        var addresses = res.data.response.cont || []
        self.formatAddressInfo(addresses) //格式化地址
        addresses.sort(function(a, b) { //根据默认字段排序，将默认地址放到最前面
          return a.fIsDefault - b.fIsDefault;
        })
        self.setData({
          list: addresses
        })
      }
    })
  },
  //格式化地址数据
  formatAddressInfo(data) {
    var self = this
    for (var i = 0; i < data.length; i++) {
      data[i].phone = data[i].fPhone.substring(0, 3) + '****' + data[i].fPhone.substring(data[i].fPhone.length - 4, data[i].fPhone.length)
      data[i].location = formatRegion(data[i].fProvinceNum, data[i].fCityNum, data[i].fAreaNum).location
      data[i].address = formatRegion(data[i].fProvinceNum, data[i].fCityNum, data[i].fAreaNum).region + '   ' + data[i].fDetailInfo
    }
    return data
  },

  //用户选择地址
  tapAddressItem(e) {
    let that = this
    if (that.data.enableSelect) { //如果存在证明是从确认订单过来的，需要选择发货地址
      const selectedAddress = this.data.list.find(i => i.fId === e.currentTarget.dataset.id)
      selectedAddress.addrTxt = formatAddrCodeToString(selectedAddress.fProvinceNum, selectedAddress.fCityNum, selectedAddress.fAreaNum) + '-' + selectedAddress.fDetailInfo || ''
      const pages = getCurrentPages()
      const prevPage = pages[pages.length - 2]
      prevPage.setData({
        showAddr: selectedAddress
      })
      wx.navigateBack()
    }
  },
  //删除地址
  tapDeleteAddress: function(e) {
    const {
      user,
      enableSelect
    } = this.data
    var self = this
    const addressList = this.data.list //记录删除之前的所有地址数据
    const addressId = e.currentTarget.dataset.id //选中删除的地址id
    wx.showModal({
      title: '提示',
      content: '确定删除此发货地址',
      success: function(res) {
        if (res.confirm) {
          wx.showLoading({
            title: '正在删除',
          })
          wx.request({
            url: deleteAddress,
            data: {
              fId: addressId,
              loginName: user.loginname,
              token: wx.getStorageSync('token')
            },
            success: function(res) {
              wx.hideLoading()
              if (res.data.code == 403) {

              } else if (res.data.code == 1) {
                wx.showToast({
                  title: res.data.code,
                  icon: 'success',
                  duration: 2000
                })
              } else {
                self.setData({
                  list: self.data.list.filter(i => i.fId !== addressId)
                }) //找到地址列表里与删除的地址的id相等的地址从列表中删除
                if (self.data.list.length != 0) {
                  for (var i = 0; i < addressList.length; i++) {
                    if (addressList[i].fId == addressId && addressList[i].fIsDefault == 0) { //如果删除的是默认地址，将第一条设置为默认地址
                      wx.request({
                        url: editAddress,
                        data: {
                          fId: self.data.list[0].fId,
                          fIsDefault: 0,
                          fUserId: user.id,
                          loginName: user.loginname,
                          token: wx.getStorageSync('token')
                        },
                        success: function(res) {
                          if (res.data.code == 0) {
                            if (enableSelect) { //如果是从订单过来的就在修改成功的时候让确认订单重新读取数据
                              const pages = getCurrentPages()
                              const prevPage = pages[pages.length - 2]
                              prevPage.loadAddress()
                            }
                            self.loadAddress() //重新读取数据
                          }
                        }
                      })
                    }
                  }
                }
                wx.showToast({
                  title: '删除成功',
                  icon: 'success',
                  duration: 2000
                })
              }
            }
          })
        } else if (res.cancel) {}
      }
    })
  },
  //设置默认地址
  setIsDefault(e) {
    const {
      user,
      enableSelect
    } = this.data
    var self = this
    var address = e.currentTarget.dataset.address //点击的当前地址信息
    wx.request({
      url: editAddress,
      data: {
        fId: address.fId,
        fIsDefault: 0,
        fUserId: user.id,
        loginName: user.loginname,
        token: wx.getStorageSync('token')
      },
      success: function(res) {
        if (res.data.code == 403) {} else if (res.data == 1) {
          wx.showToast({
            title: res.data.msg,
            icon: 'success',
            duration: 2000
          })
        } else {
          if (enableSelect) { //如果是从订单过来的就在修改成功的时候让确认订单重新读取数据
            const pages = getCurrentPages()
            const prevPage = pages[pages.length - 2]
            prevPage.loadAddress()
          }
          wx.showToast({
            title: '修改成功',
            icon: 'success',
            duration: 2000
          })
          for (var i = 0; i < self.data.list.length; i++) {
            var item = 'list[' + i + '].fIsDefault'
            if (self.data.list[i].fId == address.fId) { //将当前的地址状态改为默认
              self.setData({
                [item]: 0
              })
            } else { //将除当前以外的地址设置为非默认
              self.setData({
                [item]: 1
              })
            }
          }
        }
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.setData({
      user: app.globalData.userInfo,
      enableSelect: options.select,
      isIPX:app.globalData.isIPX
    })
    this.loadAddress()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    this.loadAddress()
    wx.stopPullDownRefresh()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})